package com.zzstm.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzstm.eduservice.entity.EduChapter;
import com.zzstm.eduservice.entity.EduComment;
import com.zzstm.eduservice.entity.EduCourse;
import com.zzstm.eduservice.entity.EduCourseDescription;
import com.zzstm.eduservice.entity.frontvo.CourseFrontVO;
import com.zzstm.eduservice.entity.frontvo.CourseWebVO;
import com.zzstm.eduservice.entity.vo.CourseInfoVO;
import com.zzstm.eduservice.entity.vo.CoursePublishVO;
import com.zzstm.eduservice.entity.vo.CourseQuery;
import com.zzstm.eduservice.mapper.EduCourseMapper;
import com.zzstm.eduservice.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzstm.servicebase.ex.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-10-30
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    private EduCourseDescriptionService courseDescriptionService;

    @Autowired
    private EduChapterService chapterService;

    @Autowired
    private EduVideoService videoService;

    @Autowired
    EduCommentService commentService;

    //添加课程信息
    @Override
    public String saveCourseInfo(CourseInfoVO courseInfoVO) {
        //1、向课程表添加信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVO, eduCourse);
        int rows = baseMapper.insert(eduCourse);
        if (rows == 0) {
            throw new GuliException(20001, "添加课程信息失败");
        }
        String cid = eduCourse.getId();
        //2、向课程简介表添加数据
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setDescription(courseInfoVO.getDescription());
        eduCourseDescription.setId(cid);
        courseDescriptionService.save(eduCourseDescription);
        return cid;
    }

    //根据课程id查询课程信息
    @Override
    public CourseInfoVO getCourseInfo(String courseId) {
        CourseInfoVO courseInfoVO = new CourseInfoVO();
        //1、先查课程表
        EduCourse eduCourse = baseMapper.selectById(courseId);
        BeanUtils.copyProperties(eduCourse, courseInfoVO);
        //2、再查课程描述表
        EduCourseDescription courseDescription = courseDescriptionService.getById(courseId);
        courseInfoVO.setDescription(courseDescription.getDescription());
        return courseInfoVO;
    }

    //修改课程信息
    @Override
    public void updateCourseInfo(CourseInfoVO courseInfoVO) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVO, eduCourse);
        int rows = baseMapper.updateById(eduCourse);
        if (rows == 0) {
            throw new GuliException(20001, "修改失败");
        }
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setId(courseInfoVO.getId());
        courseDescription.setDescription(courseInfoVO.getDescription());
        courseDescriptionService.updateById(courseDescription);
    }

    //根据课程id查询课程确认信息
    @Override
    public CoursePublishVO getPublishCourseInfo(String courseId) {
        return baseMapper.getPublishCourseInfo(courseId);
    }

    //获取所有课程
    @Override
    public List<CourseInfoVO> getCourseInfoList() {

        //1、先查课程表
        List<EduCourse> courseList = baseMapper.selectList(null);
        //2、再查课程描述表
        List<EduCourseDescription> descriptionList = courseDescriptionService.list(null);
        //创建VO集合
        List<CourseInfoVO> courseInfoVOList = new ArrayList<>();
        for (EduCourse e : courseList){
            CourseInfoVO courseInfoVO = new CourseInfoVO();
            BeanUtils.copyProperties(e, courseInfoVO);
            for (EduCourseDescription ed : descriptionList) {
                if (e.getId().equals(ed.getId())) {
                    //删除<>标签
//                    while (ed.getDescription().contains("<")){
//                        int begin = ed.getDescription().lastIndexOf("<");
//                        int end = ed.getDescription().lastIndexOf(">") + 1;
//                        String rengDiao = ed.getDescription().substring(begin,end);
//                        String xuYao = ed.getDescription().replace(rengDiao,"");
//                        ed.setDescription(xuYao);
//                    }
                    courseInfoVO.setDescription(ed.getDescription());
                }
            }
            courseInfoVOList.add(courseInfoVO);
        }
        return courseInfoVOList;
    }

    //条件查询课程
    @Override
    public Map<String, Object> pageCourseCondition(Long pageNum, Long pageSize, CourseQuery courseQuery) {
        Page<EduCourse> page = new Page<>(pageNum,pageSize);
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        String title = courseQuery.getTitle();
        String status = courseQuery.getStatus();

        if (!StringUtils.isEmpty(title)){
            wrapper.like("title",title);
        }
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("status",status);
        }
        wrapper.orderByDesc("gmt_create");
        this.page(page,wrapper);
        Map<String,Object> map = new HashMap<>();
        long total = page.getTotal();
        List<EduCourse> records = page.getRecords();

        //获取每个课程id，然后查询课程描述信息，封装在CourseInfoVO中
        List<CourseInfoVO> courseInfoVOList = new ArrayList<>();
        for (EduCourse e : records){
            CourseInfoVO courseInfoVO = new CourseInfoVO();
            BeanUtils.copyProperties(e,courseInfoVO);
            List<EduCourseDescription> descriptionList = courseDescriptionService.list(null);
            for (EduCourseDescription ed : descriptionList){
                if (e.getId().equals(ed.getId())){
                    //删除<>标签
//                    while (ed.getDescription().contains("<")){
//                        int begin = ed.getDescription().lastIndexOf("<");
//                        int end = ed.getDescription().lastIndexOf(">") + 1;
//                        String rengDiao = ed.getDescription().substring(begin,end);
//                        String xuYao = ed.getDescription().replace(rengDiao,"");
//                        ed.setDescription(xuYao);
//                    }
                    courseInfoVO.setDescription(ed.getDescription());
                }
            }
            courseInfoVOList.add(courseInfoVO);
        }
        map.put("total",total);
        map.put("courseInfoVOList",courseInfoVOList);
        return map;
    }

    @Override
    public void removeCourseById(String courseId) {
        //通过课程id删除小节
        videoService.removeVideoByCourseId(courseId);
        //通过课程id删除章节
        chapterService.removeByCourseId(courseId);
        //通过课程id删除描述
        courseDescriptionService.removeById(courseId);
        //通过课程id删除课程
        int rows = baseMapper.deleteById(courseId);
        if (rows != 1){
            throw new GuliException(20001,"删除课程失败");
        }
    }

    @Override
    public Map<String, Object> getCourseFrontList(Page<EduCourse> pageParam, CourseFrontVO courseVO) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(courseVO.getSearchName())){
            wrapper.like("title",courseVO.getSearchName());
        }
        if (!StringUtils.isEmpty(courseVO.getSubjectParentId())){
            wrapper.eq("subject_parent_id",courseVO.getSubjectParentId());
        }
        if (!StringUtils.isEmpty(courseVO.getSubjectId())){
            wrapper.eq("subject_id",courseVO.getSubjectId());
        }
        if (!StringUtils.isEmpty(courseVO.getBuyCountSort())){
            wrapper.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(courseVO.getGmtCreateSort())){
            wrapper.orderByDesc("gmt_create");
        }
        if (!StringUtils.isEmpty(courseVO.getPriceSort())){
            wrapper.orderByDesc("price");
        }
        baseMapper.selectPage(pageParam, wrapper);

        List<EduCourse> records = pageParam.getRecords();
        List<CourseInfoVO> courseInfoVOList = new ArrayList<>();
        //查询评论数
        for (EduCourse course : records){
            CourseInfoVO courseInfoVO = new CourseInfoVO();
            BeanUtils.copyProperties(course,courseInfoVO);
            QueryWrapper<EduComment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("course_id",course.getId());
            int count = commentService.count(queryWrapper);
            courseInfoVO.setCommentNum(count);
            courseInfoVOList.add(courseInfoVO);
        }
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();
        boolean hasPrevious = pageParam.hasPrevious();

        Map<String, Object> map = new HashMap<>();
        map.put("items", courseInfoVOList);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    @Override
    public CourseWebVO getBaseCourseInfo(String courseId) {
        return baseMapper.getBaseCourseInfo(courseId);
    }
}

